import type { IconProps, IconifyIcon } from "@iconify/vue";
import {
  h,
  defineComponent,
  type Component,
  type FunctionalComponent,
  type SVGAttributes,
} from "vue";
import IconifyIconOffline from "../IconifyIconOffline";
import IconifyIconOnline from "../IconifyIconOnline";

/**
 * 支持 自定义 `svg` 以及 `iconify` 中所有的图标
 * @param icon 必传 图标
 * @param attrs 可选 iconType 属性
 * @returns Component
 */
type iconType = IconifyIcon | String | FunctionalComponent<SVGAttributes, {}>;
export function useRenderIcon(
  icon: iconType,
  attrs?: Omit<IconProps, "icon"> & SVGAttributes
): Component {
  // typeof icon === "function" 属于SVG
  if (
    typeof icon === "function" ||
    typeof (icon as any)?.render === "function"
  ) {
    // svg component
    return icon;
  } else if (typeof icon === "object") {
    // 离线本地 iconify 图标
    return defineComponent({
      name: "OfflineIcon",
      render() {
        return h(IconifyIconOffline, {
          icon: icon as IconifyIcon,
          ...attrs,
        });
      },
    });
  } else {
    // 通过是否存在 : 符号来判断是在线还是本地图标，存在即是在线图标，反之
    return defineComponent({
      name: "OnlineIcon",
      render() {
        const IconifyIcon =
          icon && typeof icon === "string" && (icon as String).includes(":")
            ? IconifyIconOnline
            : IconifyIconOffline;
        return h(IconifyIcon, {
          icon: icon,
          ...attrs,
        });
      },
    });
  }
}
